﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using YGBookmark.DAL;
using YGBookmark.Models;
using Timer = System.Windows.Forms.Timer;

namespace YGBookmark.UI
{
    /// <summary>
    /// 高级查询窗体（支持多条件组合搜索和结果导出）
    /// </summary>
    public partial class QueryForm : Form
    {
        #region 控件声明
        private TableLayoutPanel mainLayout;
        private Panel filterPanel;
        private TextBox txtKeywords;
        private CheckedListBox clbTags;
        private DateTimePicker dtpStart;
        private DateTimePicker dtpEnd;
        private Button btnSearch;
        private DataGridView dgvResults;
        private ToolStripStatusLabel lblStatus;
        #endregion

        public QueryForm()
        {
            InitializeComponent();
            InitializeUI();
            LoadTags();
        }

        #region UI初始化
        private void InitializeComponent()
        {
            this.SuspendLayout();
            this.AutoScaleDimensions = new SizeF(6F, 12F);
            this.AutoScaleMode = AutoScaleMode.Font;
            this.ClientSize = new Size(1000, 600);
            this.Text = "高级书签查询";
            this.ResumeLayout(false);
        }

        private void InitializeUI()
        {
            // 主布局
            mainLayout = new TableLayoutPanel
            {
                Dock = DockStyle.Fill,
                RowCount = 3,
                ColumnCount = 1,
                RowStyles = {
                    new RowStyle(SizeType.Absolute, 120),
                    new RowStyle(SizeType.Percent, 100),
                    new RowStyle(SizeType.Absolute, 25)
                }
            };

            // 筛选面板
            filterPanel = new Panel { Dock = DockStyle.Fill };
            InitializeFilterControls();

            // 结果表格
            dgvResults = new DataGridView
            {
                Dock = DockStyle.Fill,
                AllowUserToAddRows = false,
                ReadOnly = true,
                AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill,
                SelectionMode = DataGridViewSelectionMode.FullRowSelect
            };

            // 状态栏
            var statusStrip = new StatusStrip { Dock = DockStyle.Fill };
            lblStatus = new ToolStripStatusLabel { Text = "就绪" };
            statusStrip.Items.Add(lblStatus);

            mainLayout.Controls.Add(filterPanel, 0, 0);
            mainLayout.Controls.Add(dgvResults, 0, 1);
            mainLayout.Controls.Add(statusStrip, 0, 2);

            this.Controls.Add(mainLayout);
        }

        private void InitializeFilterControls()
        {
            var layout = new TableLayoutPanel
            {
                Dock = DockStyle.Fill,
                ColumnCount = 3,
                RowCount = 3
            };

            // 关键词搜索
            txtKeywords = new TextBox { Dock = DockStyle.Fill, Tag = "关键词" };
            txtKeywords.TextChanged += (s, e) => DebounceSearch();

            // 标签选择
            clbTags = new CheckedListBox
            {
                Dock = DockStyle.Fill,
                CheckOnClick = true,
                SelectionMode = SelectionMode.None
            };

            // 日期范围
            dtpStart = new DateTimePicker { Dock = DockStyle.Fill, Format = DateTimePickerFormat.Custom, CustomFormat = " " };
            dtpEnd = new DateTimePicker { Dock = DockStyle.Fill, Format = DateTimePickerFormat.Custom, CustomFormat = " " };
            dtpStart.ValueChanged += (s, e) => UpdateDatePickerStyle(dtpStart);
            dtpEnd.ValueChanged += (s, e) => UpdateDatePickerStyle(dtpEnd);

            // 搜索按钮
            btnSearch = new Button
            {
                Text = "🔍 搜索",
                Dock = DockStyle.Fill,
                BackColor = Color.SteelBlue,
                ForeColor = Color.White
            };
            btnSearch.Click += async (s, e) => await ExecuteSearch();

            // 布局组合
            layout.Controls.Add(new Label { Text = "关键词:", AutoSize = true }, 0, 0);
            layout.Controls.Add(txtKeywords, 1, 0);
            layout.Controls.Add(new Label { Text = "标签过滤:" }, 0, 1);
            layout.Controls.Add(clbTags, 1, 1);
            layout.Controls.Add(new Label { Text = "日期范围:" }, 0, 2);
            layout.Controls.Add(new Panel { Dock = DockStyle.Fill }.WithChildren(dtpStart, dtpEnd), 1, 2);
            layout.Controls.Add(btnSearch, 2, 0);

            filterPanel.Controls.Add(layout);
        }
        #endregion

        #region 数据操作
        private async void LoadTags()
        {
            try
            {
                var tags = await DatabaseHelper.Instance.ExecuteQueryAsync<Tag>(
                    "SELECT * FROM Tags ORDER BY Name");

                clbTags.Items.Clear();
                foreach (var tag in tags)
                {
                    clbTags.Items.Add(tag.Name, false);
                }
            }
            catch (Exception ex)
            {
                ShowError($"加载标签失败: {ex.Message}");
            }
        }

        private async Task ExecuteSearch()
        {
            try
            {
                btnSearch.Enabled = false;
                lblStatus.Text = "搜索中...";

                var results = await DatabaseHelper.Instance.ExecuteQueryAsync<Bookmark>(BuildQuery(), GetParameters());

                dgvResults.DataSource = results;
                lblStatus.Text = $"找到 {results.Count} 条结果";
            }
            catch (Exception ex)
            {
                ShowError($"搜索失败: {ex.Message}");
            }
            finally
            {
                btnSearch.Enabled = true;
            }
        }

        private string BuildQuery()
        {
            var whereClauses = new List<string>();
            var joins = new List<string>();

            // 基础查询
            var sql = @"
                SELECT b.Id, b.Url, b.Title, b.Summary, 
                       GROUP_CONCAT(t.Name, ', ') AS Tags,
                       b.CreateTime 
                FROM Bookmarks b
                LEFT JOIN BookmarkTags bt ON b.Id = bt.BookmarkId
                LEFT JOIN Tags t ON bt.TagId = t.Id";

            // 关键词搜索
            if (!string.IsNullOrEmpty(txtKeywords.Text))
            {
                whereClauses.Add("(b.Title LIKE @keywords OR b.Summary LIKE @keywords)");
            }

            // 标签过滤
            var checkedTags = clbTags.CheckedItems;
            if (checkedTags.Count > 0)
            {
                joins.Add("INNER JOIN BookmarkTags bt_filter ON b.Id = bt_filter.BookmarkId");
                joins.Add($"INNER JOIN Tags t_filter ON bt_filter.TagId = t_filter.Id AND t_filter.Name IN ({string.Join(",", checkedTags.Cast<string>().Select(t => $"'{t.Replace("'", "''")}"))})");
            }

            // 日期范围
            if (dtpStart.CustomFormat != " ")
            {
                whereClauses.Add("b.CreateTime >= @startDate");
            }
            if (dtpEnd.CustomFormat != " ")
            {
                whereClauses.Add("b.CreateTime <= @endDate");
            }

            // 组合SQL
            return $@"
                {string.Join(" ", joins.Distinct())}
                WHERE {string.Join(" AND ", whereClauses.DefaultIfEmpty("1=1"))}
                GROUP BY b.Id
                ORDER BY b.CreateTime DESC";
        }

        private SQLiteParameter[] GetParameters()
        {
            var parameters = new List<SQLiteParameter>();

            if (!string.IsNullOrEmpty(txtKeywords.Text))
            {
                parameters.Add(new SQLiteParameter("@keywords", $"%{txtKeywords.Text}%"));
            }

            if (dtpStart.CustomFormat != " ")
            {
                parameters.Add(new SQLiteParameter("@startDate", dtpStart.Value.Date));
            }

            if (dtpEnd.CustomFormat != " ")
            {
                parameters.Add(new SQLiteParameter("@endDate", dtpEnd.Value.Date.AddDays(1)));
            }

            return parameters.ToArray();
        }
        #endregion

        #region UI交互
        private void UpdateDatePickerStyle(DateTimePicker picker)
        {
            picker.CustomFormat = picker.Value == DateTime.MinValue ? " " : "yyyy-MM-dd";
        }

        private void DebounceSearch()
        {
            // 实现防抖搜索（300ms）
            var timer = new Timer { Interval = 300 };
            timer.Tick += async (s, e) =>
            {
                timer.Stop();
                await ExecuteSearch();
                timer.Dispose();
            };
            timer.Start();
        }

        private void ShowError(string message)
        {
            MessageBox.Show(message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            lblStatus.Text = "操作失败";
        }
        #endregion
    }

    #region 扩展方法
    public static partial class ControlExtensions
    {
        public static Control WithChildren(this Control parent, params Control[] children)
        {
            parent.Controls.AddRange(children);
            return parent;
        }
    }
    #endregion
}